<template>
  <div class="kong">
    <el-dialog
      :title="isEdit == 1 ? '修改花销统计' : '非计划消费'"
      v-model="dataEditVisible"
      width="40%"
      :close-on-click-modal="false"
      :before-close="handelClose"
      center
    >
      <div>
        <el-form
          ref="dataEditRef"
          :rules="rules"
          :model="row"
          label-width="120px"
        >
          <el-form-item label="内容" prop="content">
            <el-input :value="row.content" v-model="row.content"></el-input>
          </el-form-item>

          <el-form-item v-if="isEdit == 0" label="计划类型" prop="expensesType">
            <el-select
              :value="row.expensesType"
              v-model="row.expensesType"
              placeholder="请选择计划类型"
            >
              <el-option
                v-for="item in expensesTypeParams"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                default-first-option
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="row.expensesType != 1"
            label="消费时间"
            prop="realTime"
          >
            <el-date-picker
              v-model="row.realTime"
              type="date"
              align="right"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="指定日期选择"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="消费金额" prop="realAmount">
            <el-input
              :value="row.realAmount"
              v-model="row.realAmount"
            ></el-input>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input :value="row.remark" v-model="row.remark"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changeStatus(!dataEditVisible, dataEditRef)"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="
              isEdit == 1
                ? submitUpdateIt(dataEditRef)
                : submitAddIt(dataEditRef)
            "
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRefs, onMounted } from 'vue'
import { FormRules, FormInstance } from 'element-plus'
import { countRows, noPlanExpenses, editCount } from '@/api/expenses'

import { selectDetail } from '@/constants/commonSelect'
import { getGroupDetail } from '@/api/config'
import { ElMessage } from 'element-plus'

const expensesTypeParams = ref<selectDetail[]>([])

let row: countRows = reactive({
  id: '0',
  expensesType: 6,
  content: '',
  remark: '',
  estimatedAmount: '',
  planStartTime: '',
  planFinishTime: '',
  realAmount: '',
  status: 0,
  realTime: '',
})

// 初始化查询
onMounted(() => {
  getExpensesType()
})

const dataEditRef = ref<FormInstance>()

interface Props {
  isEdit?: Number
  dataEditVisible?: Boolean
}

const getExpensesType = async () => {
  getGroupDetail('constgroup_expenses_type').then((res: any) => {
    // 限制条件
    res = res.filter((item: any) => {
      return item.value > 5
    })
    expensesTypeParams.value = res
  })
}

const myProps = defineProps<Props>()

const { dataEditVisible } = toRefs(myProps)

const emit = defineEmits(['dataEditConfig'])

const changeStatus = (status: boolean, formEl: FormInstance | undefined) => {
  emit('dataEditConfig', status)
  resetFields(formEl)
}

const handelClose = (done: () => void, formEl: FormInstance | undefined) => {
  changeStatus(!dataEditVisible, formEl)
  done()
}

const resetFields = (formEl: FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields()
  } else {
    dataEditRef.value?.resetFields()
  }
  row.expensesType = 6
  row.content = ''
  row.remark = ''
  row.realAmount = ''
  row.realTime = ''
}

const rules = reactive<FormRules>({
  content: [
    {
      required: true,
      message: '请输入内容',
      trigger: 'change',
    },
  ],
  realAmount: [
    {
      required: true,
      message: '请输入消费金额',
      trigger: 'change',
    },
  ],
})

const submitAddIt = async (formEl: FormInstance | undefined) => {
  console.log('submitAddIt')
  if (!formEl) {
    return
  }

  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      noPlanExpenses(row).then((res: any) => {
        if (res.data) {
          changeStatus(!dataEditVisible, formEl)
          ElMessage.success('添加成功')
        }
      })
    } else {
      console.log('error submit!', fields)
      changeStatus(!dataEditVisible, formEl)
      ElMessage.error('添加失败')
    }
  })
}

const submitUpdateIt = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }

  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('update!')
      editCount(row).then((res: any) => {
        if (res.data) {
          changeStatus(!dataEditVisible, formEl)
          ElMessage.success('编辑成功')
        }
      })
    } else {
      console.log('error update!', fields)
      changeStatus(!dataEditVisible, formEl)
      ElMessage.error('编辑失败')
    }
  })
}

const initsObj = (rows: countRows) => {
  if (rows) {
    row = rows
  }
}

defineExpose({
  initsObj,
})
</script>
```
